using System;
using UnityEngine;

namespace EntityKit.Runtime
{
    public static partial class AudioKit
    {
        private static AudioSource CreateAudioSource(string name, float volume, float speed, float spatialBlend, Transform parent, bool isMute)
        {
            try
            {
                var obj = new GameObject(name);
                if (parent != null)
                {
                    obj.transform.SetParent(parent);
                }

                var source = obj.AddComponent<AudioSource>();
                ConfigureAudioSource(source, null, false, speed);
                source.volume = volume;
                source.spatialBlend = spatialBlend;
                source.mute = isMute;
                return source;
            }
            catch (Exception ex)
            {
                Debug.LogError($"创建音频源失败: {ex.Message}");
                return null;
            }
        }

        private static AudioSource AttachAudioSource(GameObject target, float volume, bool isMute)
        {
            try
            {
                var source = target.GetOrAddComponent<AudioSource>();
                source.playOnAwake = false;
                source.volume = volume;
                source.spatialBlend = 1;
                source.mute = isMute;
                return source;
            }
            catch (Exception ex)
            {
                Debug.LogError($"附加音频源失败: {ex.Message}");
                return null;
            }
        }

        private static void ConfigureAudioSource(AudioSource source, AudioClip clip, bool isLoop, float speed)
        {
            if (source == null) return;

            if (clip != null) source.clip = clip;
            source.loop = isLoop;
            source.pitch = Mathf.Clamp(speed, -3f, 3f);
        }

        private static bool ValidateClip(AudioClip clip)
        {
            if (clip != null) return true;
            Debug.LogError("尝试播放空音频剪辑");
            return false;
        }

        private static bool ValidateTarget(GameObject target)
        {
            if (target != null) return true;
            Debug.LogError("目标对象为空");
            return false;
        }
    }
}